﻿
#include "wind_mgr.h"
#include "ui_wind.h"
#include "main_wind.h"

#define LOAD_WINDOW(T, I)                                                                                              \
    T *wnd;                                                                                                            \
    do {                                                                                                               \
        wnd = __dc(T, getWindow(I));                                                                                   \
        if (wnd) {                                                                                                     \
            LOG(WARN) << "window already exists, maybe reflush UI. ID=" << I;                                          \
            break;                                                                                                     \
        }                                                                                                              \
        LOG(INFO) << "new window. ID=" << I;                                                                           \
        wnd = new T();                                                                                                 \
        wnd->setId(I);                                                                                                 \
        regWindow(I, wnd);                                                                                             \
    } while (false)

CWindMgr *g_objWindMgr = CWindMgr::ins();

void CWindMgr::showMain() {
    new UIWindow();
}

void CWindMgr::closeWindow(int windID){
    WindowView *wv = __dc(WindowView, getWindow(windID));
    if (!wv) {
        LOG(WARN) << "close window by id, but not find. ID=" << windID;
        return;
    }

    LOG(DEBUG) << "close window by id. ID=" << windID;
    wv->exitView();
}

bool CWindMgr::exists(emWindowID ID){
    return getWindow(ID) != 0;
}

void CWindMgr::closeOther(emWindowID Id) {
    std::map<int, IWindow *> winds;

    LOG(DEBUG) << "only keep one window. id=" << Id;
    getWindows(winds);

    for (auto kv : winds) {
        int sub_id = kv.second->getId();
        if (sub_id != Id){
            LOG(VERBOSE) << "close window. id=" << sub_id;
            __dc(WindowView, kv.second)->closeView();
        }
    }
}

void CWindMgr::showWind(emWindowID ID) {
#define WINDOW_CLASS(I, C)                                                                                             \
    case I: {                                                                                                          \
        LOAD_WINDOW(C, I);                                                                                             \
    } break

    switch (ID) {
        WINDOW_CLASS(WINDOW_MAIN, MainWind);
    default: LOG(ERROR) << "not support window. id=" << ID; break;
    }
#undef WINDOW_CLASS
}
